package cn.shangqizhenshuai.sqiot.Aspect;

import cn.shangqizhenshuai.sqiot.Filter.UserLoginMap;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Type;
import java.util.Map;

/**
 * 修改action返回值（主要是token的更换）
 */
@Aspect
@Configuration
public class ResAspect {
    @Autowired
    UserLoginMap userLoginMap;

    // 定义切点Pointcut
    @Pointcut("execution(* cn.shangqizhenshuai.sqiot.action.*Action.*(..))")
    public void excudeService() {
    }
    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();
        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        Gson gson = new Gson();
        Map<String, String> m2 = (Map<String, String>) result;
        String errorcode=null;
        try {
            errorcode = m2.get("errorcode");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(StringUtils.isNotEmpty(errorcode)){

        }else{
            m2.put("errorcode","00000");
        }
        if(!errorcode.equalsIgnoreCase("00001")){
            HttpSession session = request.getSession();
            //添加到全局session容器中
            String md5Hex = DigestUtils.md5Hex(session.getId()  + "sqiot");
            userLoginMap.deluser(request.getParameter("token"));
            userLoginMap.putuser(md5Hex);
            m2.put("token",md5Hex);
        }
        return m2;

    }


}
